package com.ruoyi.tb.lmt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ExcelUtils;
import com.ruoyi.common.utils.GuidUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.tb.lmt.domain.bo.TbFdxdetailBo;
import com.ruoyi.tb.lmt.service.ITbFdxdetailService;
import com.ruoyi.tb.lmt.service.ITbWorkcategoryService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import com.ruoyi.tb.lmt.domain.bo.TbFdxBo;
import com.ruoyi.tb.lmt.domain.vo.TbFdxVo;
import com.ruoyi.tb.lmt.domain.TbFdx;
import com.ruoyi.tb.lmt.mapper.TbFdxMapper;
import com.ruoyi.tb.lmt.service.ITbFdxService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 临修主表Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-03
 */
@RequiredArgsConstructor
@Service
public class TbFdxServiceImpl implements ITbFdxService {

    private final TbFdxMapper baseMapper;

    private final ITbWorkcategoryService tbWorkcategoryService;

    private final ITbFdxdetailService iTbFdxdetailService;

    /**
     * 查询临修主表
     */
    @Override
    public TbFdxVo queryById(Long ID) {
        return baseMapper.selectVoById(ID);
    }

    /**
     * 查询临修主表列表
     */
    @Override
    public TableDataInfo<TbFdxVo> queryPageList(TbFdxBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TbFdx> lqw = buildQueryWrapper(bo);
        Page<TbFdxVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询临修主表列表
     */
    @Override
    public List<TbFdxVo> queryList(TbFdxBo bo) {
        LambdaQueryWrapper<TbFdx> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbFdx> buildQueryWrapper(TbFdxBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbFdx> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getLmtType()), TbFdx::getLmtType, bo.getLmtType());
        lqw.eq(StringUtils.isNotBlank(bo.getLmtNumber()), TbFdx::getLmtNumber, bo.getLmtNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkerteam()), TbFdx::getWorkerteam, bo.getWorkerteam());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkerteamCharge()), TbFdx::getWorkerteamCharge, bo.getWorkerteamCharge());
        lqw.eq(StringUtils.isNotBlank(bo.getTelphone()), TbFdx::getTelphone, bo.getTelphone());
        lqw.eq(bo.getMachineGroupPepoles() != null, TbFdx::getMachineGroupPepoles, bo.getMachineGroupPepoles());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckMain()), TbFdx::getCheckMain, bo.getCheckMain());
        lqw.eq(bo.getRequireStartTime() != null, TbFdx::getRequireStartTime, bo.getRequireStartTime());
        lqw.eq(bo.getRequireEndTime() != null, TbFdx::getRequireEndTime, bo.getRequireEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getPlanPerson()), TbFdx::getPlanPerson, bo.getPlanPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getApprovalUser()), TbFdx::getApprovalUser, bo.getApprovalUser());
        lqw.eq(bo.getSendTime() != null, TbFdx::getSendTime, bo.getSendTime());
        lqw.eq(StringUtils.isNotBlank(bo.getSendUser()), TbFdx::getSendUser, bo.getSendUser());
        lqw.eq(StringUtils.isNotBlank(bo.getCodeNumber()), TbFdx::getCodeNumber, bo.getCodeNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TbFdx::getStatus, bo.getStatus());
        lqw.eq(bo.getLastCheckTime() != null, TbFdx::getLastCheckTime, bo.getLastCheckTime());
        lqw.eq(StringUtils.isNotBlank(bo.getLastCheckUser()), TbFdx::getLastCheckUser, bo.getLastCheckUser());
        lqw.eq(StringUtils.isNotBlank(bo.getRepairUnit()), TbFdx::getRepairUnit, bo.getRepairUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getPlaceLine()), TbFdx::getPlaceLine, bo.getPlaceLine());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkgroupTag()), TbFdx::getWorkgroupTag, bo.getWorkgroupTag());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkType()), TbFdx::getWorkType, bo.getWorkType());
        return lqw;
    }

    /**
     * 新增临修主表
     */
    @Override
    public Boolean insertByBo(TbFdxBo bo) {
        TbFdx add = BeanUtil.toBean(bo, TbFdx.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setID(add.getID());
        }
        return flag;
    }

    /**
     * 修改临修主表
     */
    @Override
    public Boolean updateByBo(TbFdxBo bo) {
        TbFdx update = BeanUtil.toBean(bo, TbFdx.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbFdx entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除临修主表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public String updateExcel(MultipartFile file) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        TbFdxBo tbFdx = null;
        TbFdxdetailBo tbFdxdetailBo = null;
        try {
            //检索Excel表
            Sheet sheet = ExcelUtils.getSheet(file.getInputStream(), file.getOriginalFilename(), 0);
            //遍历表行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                //判断是否为空，为空的情况跳出
                Row row = sheet.getRow(i);
                if (StringUtils.isBlank(getVal(row.getCell(0)))) {
                    return "";
                }
                tbFdx = new TbFdxBo();
                tbFdx.setID(GuidUtil.getZcbhid());

                tbFdx.setLmtNumber(getVal(row.getCell(0)));
                tbFdx.setLmtType(getVal(row.getCell(1)));

                tbFdx.setRequireStartTime(row.getCell(2).getDateCellValue() == null ? null : row.getCell(2).getDateCellValue());
                tbFdx.setWorkType("预检");
                tbFdx.setStatus("新提票");
                LoginUser currentUser = LoginHelper.getLoginUser();
                tbFdx.setCreateTime(new Date());
                tbFdx.setCreateBy(currentUser.getUsername());

                //新增详情表
                tbFdxdetailBo = new TbFdxdetailBo();
                tbFdxdetailBo.setFdxId(tbFdx.getID());
                tbFdxdetailBo.setWorkName(getVal(row.getCell(3)));
                tbFdxdetailBo.setWorkKind(getVal(row.getCell(4)));
                tbFdxdetailBo.setWorkCategory(getVal(row.getCell(5)));
                if (StringUtils.isBlank(tbFdxdetailBo.getWorkKind())) {
                    return "检修类别不能为空";
                }
                String id = tbWorkcategoryService.selectIdByPidAndName("0", tbFdxdetailBo.getWorkKind(), tbFdx.getLmtType());
                if (StringUtils.isBlank(tbFdxdetailBo.getWorkCategory())) {
                    tbFdxdetailBo.setWorkCategory(id);
                } else {
                    String s = tbWorkcategoryService.selectIdByPidAndName(id, tbFdxdetailBo.getWorkKind(), tbFdx.getLmtType());
                    tbFdxdetailBo.setWorkCategory(s);
                }
                tbFdxdetailBo.setWorkGroup(getVal(row.getCell(6)));
                tbFdxdetailBo.setWorkGroup2(getVal(row.getCell(7)));
                tbFdxdetailBo.setWorkCategoryRemark(getVal(row.getCell(8)));
                tbFdxdetailBo.setStatus("未提报");
                tbFdxdetailBo.setCheckReapirReqire(getVal(row.getCell(9)));
                tbFdxdetailBo.setCreateTime(new Date());
                tbFdxdetailBo.setCreateBy(currentUser.getUsername());
                insertByBo(tbFdx);
                iTbFdxdetailService.insertByBo(tbFdxdetailBo);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "批量添加操作失败";
        }


        return "";
    }

    @Override
    public void export(HttpServletRequest request, HttpServletResponse response) {
        // 创建一个Excel工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建一个工作表sheet
        Sheet sheet = workbook.createSheet("预检提交");

        // 创建标题行
        Row titleRow = sheet.createRow(0);

        // 定义标题行的列名
        String[] columnHeaders = {
            "车号", "车型", "作业时间", "检修内容", "检修类型父级", "检修类型", "检修工队", "辅修工队", "检修备注", "技术要求"

        };

        // 设置单元格样式（可选）
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);

        // 创建标题行单元格并写入列名
        for (int i = 0; i < columnHeaders.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(columnHeaders[i]);
            cell.setCellStyle(headerStyle);
        }
        // 设置所有行高
        for (Row row : sheet) {
            row.setHeightInPoints(20);
        }

        // 设置所有列宽
        for (Sheet sh : workbook) {
            for (int i = 0; i < 300; i++) {
                sh.setColumnWidth(i, 14 * 256);
            }
        }

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            //os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String getVal(Cell cell) {
        if (cell == null) {
            return "";
        }
        return cell.getStringCellValue();
    }

    public class ExecutionException extends RuntimeException {
        public ExecutionException(String message) {
            super(message);
        }
    }

}






